#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include "msg_queue.h"
#include "struct.h"
#include "tools.h"


static int msgid_ctos;
static int msgid_stoc;

Msg_ctos msg_ctos;
Msg_stoc msg_stoc;

void login_acc(void)
{
	char acc_path[255] = {};
	
	sprintf(acc_path,"%s%u",ACCOUNT_PATH,msg_ctos.m_acc.id);
	
	if(-1 == access(acc_path,F_OK))
	{
		sprintf(msg_stoc.m_str,"帐号：%d 不存在",msg_ctos.m_acc.id);
		return;
	}
	
	int fd = open(acc_path,O_RDWR);
	if(0 > fd)
	{
		perror("open");
		sprintf(msg_stoc.m_str,"Landing...");
		return;
	}
	
	Acc acc = {};
	if(0 >= read(fd,&acc,sizeof(acc)))
	{
		perror("read");
		sprintf(msg_stoc.m_str,"Landing...");
		return;
	}
	
	if(3 == acc.lock)
	{
		sprintf(msg_stoc.m_str,"帐号已锁定...");
		return;
	}
	
	if(0 != strcmp(acc.pswd,msg_ctos.m_acc.pswd))
	{
		acc.lock++;
		lseek(fd,0,SEEK_SET);
		if(0 >= write(fd,&acc,sizeof(acc)))
		{
			perror("write");
			sprintf(msg_stoc.m_str,"Landing...");
			return;
		}
		sprintf(msg_stoc.m_str,"用户或密码错误...");
		return;
	}
	
	acc.lock = 0;	
	lseek(fd,0,SEEK_SET);
	if(0 >= write(fd,&acc,sizeof(acc)))
	{
		perror("write");
		sprintf(msg_stoc.m_str,"Landing...");
		return;
	}
	
	strcpy(msg_stoc.m_str,"登录成功");
}


int main()
{
	msgid_ctos = get_ctos_msg();
	msgid_stoc = get_stoc_msg();
	
	while(1)
	{
		if(-1 == msgrcv(msgid_ctos,&msg_ctos,sizeof(msg_ctos),M_LOGIN,0))
		{
			perror("msgrcv");
		}
		
		login_acc();
		
		msg_stoc.m_type = msg_ctos.m_pid;
		
		if(-1 == msgsnd(msgid_stoc,&msg_stoc,sizeof(msg_stoc.m_str),0))
		{
			perror("msgsnd");
		}
	}
}

